package com.summer.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.reggie.common.BaseContext;
import com.summer.reggie.common.CustomException;
import com.summer.reggie.entity.*;
import com.summer.reggie.mapper.OrdersMapper;
import com.summer.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 作者:夏天
 * qq:1205232048
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //得到用户Id
        Long userId = BaseContext.getCurrentId();
        //根据用户Id得到购物车
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        //判断购物车是否为空, 为空抛出异常
        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空, 下单失败");
        }
        //购物车不为空, 根据用户Id得到用户数据
        User user = userService.getById(userId);
        //根据订单得到地址Id
        Long addressBookId = orders.getAddressBookId();
        //根据地址Id得到地址数据
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //判断地址是否为空, 为空则抛出异常
        if(addressBook == null){
            throw new CustomException("地址信息为空, 下单失败");
        }
        //创建一个订单Id
        long orderId = IdWorker.getId();
        //计算总金额 与 封装OrdersDetail表数据
        AtomicInteger amount = new AtomicInteger(0);//总金额 线程安全
        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //向Orders表封装好数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //给Orders表插入数据
        this.save(orders);
        //给OrdersDetail表插入数据
        orderDetailService.saveBatch(orderDetailList);
        //清空购物车
        shoppingCartService.remove(queryWrapper);
    }
}
